<template>
  <div class="bankaccount-container">
    <!-- 银行卡信息展示区域 -->
       <div v-if="hasBankAccount" class="bank-form-section">
      <el-card>
        <template #header>
          <div class="form-header">
            <h3>
              <span>銀行カード</span>
            </h3>
          </div>
        </template>
        <div style="    color: #f35d12;
    font-size: 1rem;">
          現在の残高:
          <p style="font-size: clamp(1.25rem, .5vw + 1rem, 1.5rem);
    font-weight: 600;
    line-height: 1.2;
    margin: 0 0 20px;
    color: #468ccb;">{{ money }} 円</p>
        </div>
        <el-form :model="bankForm" :rules="bankRules" ref="bankFormRef" label-position="top" class="bank-form">
          <el-form-item label="銀行名" prop="banks_id">
            <el-select v-model="bankForm.banks_id" placeholder="请选择银行" style="width: 100%" disabled>
              <el-option v-for="bank in banksList" :key="bank.id" :label="bank.name" :value="bank.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="支店名" prop="banks_branch">
            <el-input v-model="bankForm.banks_branch" placeholder="请输入支行名称" disabled></el-input>
          </el-form-item>

          <el-form-item label="口座種類" prop="account_type">
            <el-select v-model="bankForm.account_type" placeholder="请选择账户类型" style="width: 100%" disabled>
              <el-option value="普通預金" label="普通預金口座"></el-option>
              <el-option value="当座預金" label="当座預金"></el-option>
              <el-option value="貯蓄預金" label="貯蓄預金"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="口座番号" prop="banks_card">
            <el-input v-model="bankForm.banks_card" placeholder="请输入账户号码" disabled></el-input>
          </el-form-item>

          <el-form-item label="口座名義人名" prop="banks_user">
            <el-input v-model="bankForm.banks_user" placeholder="请输入账户持有人姓名" disabled></el-input>
          </el-form-item>
        </el-form>
        <el-form-item class="form-buttons">
          <!-- <div class="button-container"> -->
            <!-- <el-button type="primary" @click="submitBankInfo" :loading="isSubmitting" style="width: 470px; background-color: #409EFF;">銀行口座を確認</el-button> -->
          <!-- </div> -->
        </el-form-item>
      </el-card>
    </div>

    <!-- 添加银行卡表单 -->
    <div v-if="!hasBankAccount || showForm" class="bank-form-section">
      <el-card>
        <template #header>
          <div class="form-header">
            <h3>
              <span>銀行カード</span>
            </h3>
          </div>
        </template>
        <div style="    color: #f35d12;
    font-size: 1rem;">
          現在の残高:
          <p style="font-size: clamp(1.25rem, .5vw + 1rem, 1.5rem);
    font-weight: 600;
    line-height: 1.2;
    margin: 0 0 20px;
    color: #468ccb;">{{ money }} 円</p>
        </div>
        <el-form :model="bankForm" :rules="bankRules" ref="bankFormRef" label-position="top" class="bank-form">
          <el-form-item label="銀行名" prop="banks_id">
            <el-select v-model="bankForm.banks_id" placeholder="選択した銀行" style="width: 100%">
              <el-option v-for="bank in banksList" :key="bank.id" :label="bank.name" :value="bank.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="支店名" prop="banks_branch">
            <el-input v-model="bankForm.banks_branch" ></el-input>
          </el-form-item>

          <el-form-item label="口座種類" prop="account_type">
            <el-select v-model="bankForm.account_type"  style="width: 100%" disabled>
              <el-option value="普通預金" label="普通預金口座"></el-option>
              <el-option value="当座預金" label="当座預金"></el-option>
              <el-option value="貯蓄預金" label="貯蓄預金"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="口座番号" prop="banks_card">
            <el-input v-model="bankForm.banks_card" ></el-input>
          </el-form-item>

          <el-form-item label="口座名義人名" prop="banks_user">
            <el-input v-model="bankForm.banks_user" ></el-input>
          </el-form-item>
        </el-form>
        <el-form-item class="form-buttons">
          <!-- <div class="button-container"> -->
            <el-button type="primary" @click="submitBankInfo" :loading="isSubmitting" style="width: 470px; background-color: #409EFF;">銀行口座を確認</el-button>
          <!-- </div> -->
        </el-form-item>
      </el-card>
    </div>

    <!-- 提示信息 -->
    <div v-if="!hasBankAccount && !showForm" class="bank-notice">
      <el-empty description="您还没有添加银行账户">
        <el-button type="primary" @click="showForm = true">
          <el-icon>
            <Plus />
          </el-icon>
          <span>立即添加</span>
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, CreditCard, Plus, View, Hide } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { userApi } from '../../../api/index'

// 初始化路由
const router = useRouter()

// 表单引用
const bankFormRef = ref(null)

// 状态变量
const hasBankAccount = ref(true)
const showForm = ref(false)
const isSubmitting = ref(false)
const banksList = ref([])
const showFullCardNumber = ref(false) // 控制是否显示完整卡号
const showFullMoney = ref(false) // 控制是否显示完整余额

const money = ref(0)
// 银行账户信息
const bankInfo = reactive({
  banks_id: '',
  banks_name: '',
  banks_branch: '',
  account_type: '',
  banks_card: '',
  banks_user: ''
})

// 表单数据
const bankForm = reactive({
  banks_id: '',
  banks_branch: '',
  account_type: '普通預金',
  banks_card: '',
  banks_user: ''
})

// 表单验证规则
const bankRules = {
  // banks_id: [
  //   { required: true, message: '请选择银行', trigger: 'change' }
  // ],
  // banks_branch: [
  //   { required: true, message: '请输入支行名称', trigger: 'blur' },
  //   { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  // ],
  // account_type: [
  //   { required: true, message: '请选择账户类型', trigger: 'change' }
  // ],
  // banks_card: [
  //   { required: true, message: '请输入账户号码', trigger: 'blur' },
  //   { pattern: /^\d{10,20}$/, message: '账户号码必须为10-20位数字', trigger: 'blur' }
  // ],
  // banks_user: [
  //   { required: true, message: '请输入账户持有人姓名', trigger: 'blur' },
  //   { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  // ]
}

// 获取银行列表
const getBanksList = async () => {
  try {
    const res = await userApi.getBanksList()
    if (res.code === 1 && res.data) {
      banksList.value = res.data
    } else {
      ElMessage.error('获取银行列表失败')
    }
  } catch (error) {
    console.error('获取银行列表失败:', error)
    ElMessage.error('获取银行列表失败')
  }
}

// 获取银行账户信息
const getBankAccountInfo = async () => {
  try {
    const res = await userApi.getBankAccount()
    if (res.code === 1 && res.data && res.data.banks) {
      // 更新银行账户信息
      Object.assign(bankInfo, res.data.banks)
      hasBankAccount.value = true
      money.value = res.data.money
      
      // 将银行卡数据填充到表单中进行显示
      Object.assign(bankForm, {
        banks_id: res.data.banks.banks_id,
        banks_branch: res.data.banks.banks_branch,
        account_type: res.data.banks.account_type || '普通預金',
        banks_card: res.data.banks.banks_card,
        banks_user: res.data.banks.banks_user
      })
    } else {
      // 没有银行账户信息
      hasBankAccount.value = false

      // 如果是从其他页面跳转过来的，自动显示添加表单
      showForm.value = true
    }
  } catch (error) {
    console.error('获取银行账户信息失败:', error)
    ElMessage.error('获取银行账户信息失败')
    hasBankAccount.value = false
    showForm.value = true
  }
}

// 显示编辑表单
const showEditForm = () => {
  // 复制当前银行信息到表单
  Object.assign(bankForm, {
    banks_id: bankInfo.banks_id,
    banks_branch: bankInfo.banks_branch,
    account_type: bankInfo.account_type,
    banks_card: bankInfo.banks_card,
    banks_user: bankInfo.banks_user
  })
  showForm.value = true
}

// 取消编辑
const cancelEdit = () => {
  showForm.value = false
  // 重置表单
  bankFormRef.value.resetFields()
}

// 提交银行信息
const submitBankInfo = async () => {
  bankFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        isSubmitting.value = true

        // 调用API提交银行账户信息
        const res = await userApi.updateBankAccount(bankForm)

        if (res.code === 1) {
          // 更新本地数据
          Object.assign(bankInfo, bankForm)
          hasBankAccount.value = true
          showForm.value = false

          ElMessage.success(res.msg || (hasBankAccount.value ? '银行账户信息已更新' : '银行账户已添加'))

          // 如果是从其他页面跳转过来的，可以返回上一页
          const urlParams = new URLSearchParams(window.location.search)
          if (urlParams.has('redirect')) {
            router.push(urlParams.get('redirect'))
          }
        } else {
          ElMessage.error(res.msg || '提交银行账户信息失败')
        }
      } catch (error) {
        console.error('提交银行账户信息失败:', error)
        ElMessage.error('提交银行账户信息失败')
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

// 掩码账号
const maskAccountNumber = (accountNumber) => {
  if (!accountNumber) return ''
  const length = accountNumber.length
  if (length <= 4) return accountNumber

  const visiblePart = accountNumber.slice(-4)
  const maskedPart = '*'.repeat(length - 4)
  return maskedPart + visiblePart
}

// 格式化金额
const formatMoney = (amount) => {
  if (amount === undefined || amount === null) return '0.00'
  
  // 转换为数字并保留两位小数
  const num = parseFloat(amount)
  if (isNaN(num)) return '0.00'
  
  // 使用toLocaleString格式化数字，添加千位分隔符
  return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 页面加载时获取银行列表和银行账户信息
onMounted(() => {
  getBanksList()
  getBankAccountInfo()
})
</script>

<style scoped>
.bankaccount-container {
  padding: 20px;
  max-width: 510px;
  margin: 0 auto;
}

@media screen and (max-width: 768px) {
  .bankaccount-container {
    /* padding: 10px; */
    /* width: 200px; */
    margin: auto;
  }
}

.balance-item {
  margin-bottom: 15px;
  padding: 10px;
  background: linear-gradient(135deg, #4e85f5 0%, #006ab6 100%);
  border-radius: 8px;
  color: white;
}

.balance-item .label {
  color: rgba(255, 255, 255, 1);
  font-weight: 700;
}

.balance-item .money {
  font-size: 16px;
  font-weight: 700;
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  letter-spacing: 1px;
}

.balance-item .value-with-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.balance-item .money-toggle-btn {
  color: rgba(255, 255, 255, 0.9);
  margin-left: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.balance-item .money-toggle-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.bank-info-section,
.bank-form-section,
.bank-notice {
  margin: auto;
  margin-top: 0px;
  width: auto;
}

.bank-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.bank-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.bank-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.bank-card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #409EFF;
  display: flex;
  align-items: center;
}



.bank-card-content {
  padding: 10px 0;
  display: flex;
  align-items: flex-start;
}

.bank-card-icon {
  margin-right: 20px;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bank-card-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.bank-info-details {
  flex: 1;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  width: 120px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.value.highlight {
  color: #ffffff;
  font-weight: 600;
}

.value.card-number {
  font-family: monospace;
  letter-spacing: 1px;
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  width: auto;
}

.value-with-action {
  display: flex;
  align-items: center;
  gap: 10px;
}

.value-with-action .el-button {
  padding: 4px 8px;
  font-size: 12px;
  height: auto;
  margin-left: 8px;
}

.value-with-action .el-button .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.form-header {
  display: flex;
  flex-direction: column;
}

.form-header h3 {
  margin: 0;
  font-size: 18px;
  display: flex;
  align-items: center;
}

.form-header h3 .el-icon,
.bank-card-header h3 .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.el-button .el-icon {
  margin-right: 4px;
}

.form-tip {
  margin: 10px 0 0;
  color: #909399;
  font-size: 14px;
}

.bank-form {
  margin-top: 20px;
}

.bank-form :deep(.el-form-item__label::before) {
  display: none !important;
}

.form-buttons {
  margin-top: 30px;
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 15px;
  width: 100%;
}

.button-container .el-button {
  min-width: 80px;
  flex: 1;
  max-width: 120px;
}

@media screen and (max-width: 768px) {
  .button-container {
    flex-direction: column;
    align-items: center;
  }

  .button-container .el-button {
    width: 100%;
    margin-left: 0;
    margin-bottom: 10px;
  }
}

.bank-notice {
  text-align: center;
  padding: 40px 0;
}
</style>